<?php

namespace App\Exceptions;

use App\Http\Controllers\Traits\JsonResponse;
use EasyWeChat\Kernel\Exceptions\HttpException;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Overtrue\Socialite\AuthorizeFailedException;
use Symfony\Component\HttpFoundation\Response;

class Handler extends ExceptionHandler
{
    use JsonResponse;
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof HttpException) {
            return $this->failed($exception->getMessage(), $exception->getCode(), Response::HTTP_INTERNAL_SERVER_ERROR);
        } else if ($exception instanceof ValidationException) {
            return response()->json([
                'error' => Response::HTTP_UNPROCESSABLE_ENTITY,
                'msg' => collect($exception->errors())->first()[0],
                'errors' => $exception->errors(),
            ])->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY);
        } else if ($exception instanceof AuthenticationException) {
            return response()->json([
                'msg' => '登录认证失败',
                'error' => Response::HTTP_UNAUTHORIZED,
            ])->setStatusCode(Response::HTTP_UNAUTHORIZED);
        } else if ($exception instanceof AuthorizeFailedException) {
            return response()->json([
                'msg' => $exception->getMessage(),
                'error' => $exception->getCode(),
            ])->setStatusCode(Response::HTTP_UNAUTHORIZED);
        }

        return parent::render($request, $exception);
    }
}
